import os
import stripe
from datetime import datetime
from flask import Flask, render_template, jsonify, request, make_response, send_from_directory
from . import app

stripe.api_key = os.environ['STRIPE_SECRET']
stripe.api_version = '2020-08-27'

@app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
    donate_amount = float(request.json['amount'])
    donate_currency = request.json['currency'].lower()
    cancel_dest = request.json['backdest']
    tshirt = request.json['tshirt']
    tshirt_size = request.json['tshirt_size']

    if cancel_dest is None:
        cancel_dest = ''

    checkout_type = 'donate'
    unit_amount = int( 100 * donate_amount )
    qty = 1
    product = 'Donation Supporting KiCad'
    desc = 'Your contribution is critical to building the next version of KiCad.  Thank you.'

    payment_types = []
    if donate_currency == 'cny':
        payment_types = ['alipay']
    elif donate_currency == 'gbp':
        payment_types = ['card']
    elif donate_currency == 'jpy':
        payment_types = ['card']
    elif donate_currency == 'eur':
        payment_types = ['sepa_debit', 'ideal', 'card']
    elif donate_currency == 'inr':
        payment_types = ['card']
    else:
        donate_currency = 'usd'
        payment_types = ['card']

    if donate_amount < 5:
        return make_response( 'Invalid Amount', 400 )

    if donate_currency == 'cny':
        checkout_type = 'auto'
        product = 'KiCad Development Unit'
        qty = int( donate_amount / 10 )
        unit_amount = 1000
        desc = 'Your purchase funds the next version of KiCad.'
    elif donate_currency == 'jpy':
        checkout_type = 'auto'
        product = 'KiCad Development Unit'
        desc = 'Your purchase funds the next version of KiCad.'
        unit_amount = int( donate_amount )

    address_allowed = None
    items=[{
            'price_data': {
            'currency': str(donate_currency).lower(),
            'product_data': {
                'name': product,
            },
            'unit_amount': unit_amount,
            },
            'quantity': qty,
            'description': desc
        }]

    if tshirt == 'yes':
        items.append({
            'price_data': {
            'currency': str(donate_currency).lower(),
            'product_data': {
                'name': 'Support KiCad T-Shirt - ' + tshirt_size,
            },
            'unit_amount': 0,
            },
            'quantity': 1
        })

        address_allowed = {
            'allowed_countries': [
                'AC', 'AD', 'AE', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AT', 'AU',
                'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ',
                'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BV', 'BW', 'BZ', 'CA', 'CD',
                'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CV', 'CW',
                'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EE', 'EG', 'EH', 'ER',
                'ES', 'ET', 'FI', 'FJ', 'FK', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF',
                'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU',
                'GW', 'GY', 'HK', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN',
                'IO', 'IQ', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI',
                'KM', 'KN', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR',
                'LS', 'LT', 'LU', 'LV', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MK', 'ML',
                'MM', 'MO', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ',
                'NA', 'NC', 'NE', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM',
                'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT',
                'PY', 'QA', 'RE', 'RO', 'RS', 'RW', 'SA', 'SB', 'SC', 'SE', 'SG', 'SH',
                'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'ST', 'SV', 'SX', 'SZ',
                'TA', 'TC', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TM', 'TN', 'TO', 'TR', 'TT',
                'TV', 'TW', 'TZ', 'UA', 'UG', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG',
                'VN', 'VU', 'WF', 'WS', 'XK', 'YT', 'ZA', 'ZM', 'ZW', 'ZZ'
            ]
        }

    session = stripe.checkout.Session.create(
        submit_type=checkout_type,
        payment_method_types=payment_types,
        line_items=items,
        metadata = { 'origin' : cancel_dest },
        mode='payment',
        shipping_address_collection=address_allowed,
        success_url='https://go.kicad.org/thank-you',
        cancel_url='https://www.kicad.org' + cancel_dest,
    )


    return jsonify(id=session.id)

@app.route("/")
def home():
    response = make_response(render_template("donate.html"))
    response.headers['Content-Security-Policy'] = "frame-ancestors 'self' https://kicad.org https://*.kicad.org;"
    return response

@app.route("/.well-known/apple-developer-merchantid-domain-association")
def get_data():
    return app.send_static_file("apple.txt")

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static', 'favicons'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')